<?php

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            if (isset($_SERVER['HTTP_X_REAL_HOST'])) {
                $host = $_SERVER['HTTP_X_REAL_HOST'];
            } else {
                $host = $_SERVER['HTTP_HOST'];
            }
            $domainArr[] = strpos($host, ':') ? strstr($host, ':', true) : $host;
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}

if (!function_exists('curl_request')) {
    /**
     * curl请求
     * @param url string 路径
     * @param type string 请求类型 get / post
     * @param param array 请求参数
     * @copyright CURL操作 解析Api通用
     */
    function curl_request($url_ = null, $type = 'get', $param = [], $headers = [], bool $is_json = false)
    {
        // get请求 url为空时默认走小程序获取
        if (empty($url_) && $type == 'get' && !empty($param)) {
            $url = 'https://api.weixin.qq.com/sns/jscode2session?' . http_build_query($param);
        }
        // get 请求
        if (!empty($url_) && $type == 'get' && !empty($param)) {
            $url = $url_ . '?' . http_build_query($param);
        }
        // post 请求
        if (!empty($url_) && $type == 'post' && !empty($param)) {
            $url = $url_;
        }
        // param 为空的使用 get
        if (!empty($url_) && $type == 'get' && empty($param)) {
            $url = $url_;
        }

        if (!empty($url_) && $type == 'post' && empty($param)) {
            $url = $url_;
        }

        $ch = curl_init();
        // 设置URL
        curl_setopt($ch, CURLOPT_URL, $url);
        // 设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // 设定是否显示头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 如果你想把一个头包含在输出中，设置这个选项为一个非零值。
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 设置一个长整形数，作为最大延续多少秒。
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        // 验证对等方的证书,false = 阻止验证 true = 验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 检查SSL对等证书中是否存在公用名 / 检查是否存在公用名，并验证它是否与提供的主机名匹配
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 输出解析的数据
        $data = curl_exec($ch);
        // 关闭 curl 资源
        curl_close($ch);
        // 返回 curl 解析被json格式化后的数据
        if ($is_json == false) {
            return json_decode($data, true);
        } else {
            return $data;
        }
    }
}

if (!function_exists('push_control')) {
    /**
     * 推送中控
     * @param string $msgType 请求类别
     * @param array $content 请求数据
     * @return mixed
     */
    function push_control($msgType, $content = [])
    {
        // 请求地址
        $linkUrl = config('control.url');
        // 设置内容
        $content['account'] = config('control.account');
        // 设置header
        $token = config('control.secret_key');
        $header = array("Content-type:application/json", "token:" . $token);
        $digest = base64_encode(md5(json_encode($content) . $token, true));//生成签名
        $data = [
            'request_type' => $msgType,
            'data_digest' => $digest,
            'content' => json_encode($content),
        ];
        $json = curl_request($linkUrl, 'post', json_encode($data), $header, true);
        $result = json_decode($json, true);
        return $result;
    }
}

if (!function_exists('recursion')) {
    /**
     * 递归数组-递归字段可自定义
     */
    function recursion($data, $pid = 0, $field = 'pid')
    {
        $array = [];
        foreach ((array)$data as $key => $val) {
            if ($val[$field] == $pid) {
                $array[] = $val;
            }
        }
        if (empty($array)) {
            return null;
        }
        //取出下一级
        foreach ($array as $key => $value) {
            $next = recursion($data, $value['id']);
            if ($next) {
                $array[$key]['next'] = $next;
            }
        }
        return $array;
    }
}

if (!function_exists('get_domain')) {
    /**
     * 获取域名
     */
    function get_domain()
    {
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type . $_SERVER['HTTP_HOST'];
    }
}

if (!function_exists('replace_imgs_url')) {
    /**
     * 转换图片路径
     */
    function replace_imgs_url($str = '')
    {
        if (strpos($str, 'https://') === false && strpos($str, 'http://') === false) {
            $str = str_replace('/uploads/', get_domain() . '/uploads/', $str);
        } else if (strpos($str, 'http://') !== false && strpos($str, 'haofenlianmeng.com') !== false) {
            $str = str_replace('http', 'https', $str);
        }
        return $str;
    }
}

if (!function_exists('replace_imgs_arr_url')) {
    /**
     * 转换图片数组路径
     */
    function replace_imgs_arr_url($arr = [])
    {
        foreach ($arr as &$val) {
            if (strpos($val, 'https://') === false && strpos($val, 'http://') === false) {
                $val = str_replace('/uploads/', get_domain() . '/uploads/', $val);
            } else if (strpos($val, 'http://') !== false && strpos($val, 'haofenlianmeng.com') !== false) {
                $val = str_replace('http', 'https', $val);
            }
        }
        return $arr;
    }
}

if (!function_exists('replace_ueditor_imgs_url')) {
    /**
     * 转换编辑器的图片路径
     */
    function replace_ueditor_imgs_url($str = '')
    {
        if (strpos($str, 'https://') === false && strpos($str, 'http://') === false) {
            $str = str_replace('/uploads/ueditor', get_domain() . '/uploads/ueditor', $str);
        } else if (strpos($str, 'http://') !== false && strpos($str, 'haofenlianmeng.com') !== false) {
            $str = str_replace('http', 'https', $str);
        }
        return $str;
    }
}

if (!function_exists('uuid')) {
    /**
     * 获取全球唯一标识
     */
    function uuid()
    {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }
}
if (!function_exists('get_encrypt_password')) {
    /**
     * 获取密码加密后的字符串
     */
    function get_encrypt_password($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
}
